package com.javaeye.chenweihuacwh.dao.baseData;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.chenweihuacwh.dto.DTO;
import com.javaeye.chenweihuacwh.dto.baseData.Product;

public class ProductDAOHibernate extends HibernateDaoSupport implements ProductDAO {
	
	public long getProductCountByCategoryId(int categoryId) {
		String sql = "select count(p.id) from Product p where p.category=" + categoryId;
		List result = getHibernateTemplate().find(sql);
		long count = 0;
		if (result.size() > 0) {
			count = (Long)result.get(0);
		}
		return count;
	}
	
	public long getAllCount(DTO contidions) {
		String sql = "select count(p.id) from Product p";
		Product product = (Product)contidions;
		if (Integer.parseInt(product.getCategory()) == -1) {
			if (!"".equals(product.getName().trim())) {
				sql += " where p.name like '%" + product.getName() + "%'";
			}
		} else {
			sql += " where p.category=" + product.getCategory();
			if (!"".equals(product.getName().trim())) {
				sql += " and p.name like '%" + product.getName() + "%'";
			}
		}
		List result = getHibernateTemplate().find(sql);
		long count = 0;
		if (result.size() > 0) {
			count = (Long)result.get(0);
		}
		return count;
	}
	
	public List getPageData(final DTO contidions, final int pageIndex, final int pageSize) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				String sql = "from Product p";
				Product product = (Product)contidions;
				if (Integer.parseInt(product.getCategory()) == -1) {
					if (!"".equals(product.getName())) {
						sql += " where p.name like '%" + product.getName() + "%'";
					}
				} else {
					sql += " where p.category=" + product.getCategory();
					if (!"".equals(product.getName())) {
						sql += " and p.name like '%" + product.getName() + "%'";
					}
				}
				Query q = session.createQuery(sql);
				q.setFirstResult(pageIndex * pageSize);
				q.setMaxResults(pageSize);
				return q.list();
			}
		};
		return (List<DTO>)getHibernateTemplate().executeFind(action);
	}
	
	@Override
	public void saveProduct(Product product) {
		getHibernateTemplate().saveOrUpdate(product);
		logger.debug("Product id set to: " + product.getId());
	}

	@Override
	public Product getProduct(int id) {
		return (Product)getHibernateTemplate().get(Product.class, id);
	}

	@Override
	public void removeProduct(int id) {
		Object o = getHibernateTemplate().get(Product.class, id);
		getHibernateTemplate().delete(o);
	}

}
